package com.openlab.callsystem.service.impl;

import com.openlab.callsystem.service.VerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;
@Service
public class VerifyServiceImpl implements VerifyService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public String generateCode(String key){
        Random rand=new Random();
        StringBuilder sb=new StringBuilder();
        for (int i=0;i<4;i++){
            sb.append(rand.nextInt(9));
        }
        String code= sb.toString();
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        return code;
    }
    @Override
    public String obtainCode(String key){
        System.out.println(key);
        String code  = (String) redisTemplate.opsForValue().get(key);
        if (code!=null){
            return code;
        }else {
            code=generateCode(key);
        }
        return code;
    }

    @Override
    public boolean confirmCode(Integer code,String key) {
        String email= (String) redisTemplate.opsForValue().get("windowsId"+key);
        return String.valueOf(code).equals(redisTemplate.opsForValue().get(email));
    }
}
